<?php
/**
 * Add a candidate to a mission
 * 
 * @package Mission
 * @author Xavier VILAIN
 */

use Hive\Mission\Partner;
use Hive\Mission;

$xview = Xview::instance();
$missionid = $xview->val("missionid");
$jsonContacts = $xview->val("data",$xview->val("checked"));
if(!empty($jsonContacts)) {
	$jsonContacts = str_replace("'",'"',$jsonContacts);
	$contacts = json_decode($jsonContacts,true);
	$nbContact = count($contacts);
	try {
		$mission = Fox\Dao::load(Mission::className(),$missionid);
		$role = Partner::ROLE_CANDIDATE;
		// Posted date
		if(!empty($contacts) && count($contacts) > 0)
		{
			foreach($contacts as $partnerid)
			{
				$partner = $mission->findPartners("$missionid:$role:$partnerid");
				if($partner->exists()) {
					$nbContact--;
				} else {
					$partner = new Partner();
					$partner->setFields(array('missionid' => $missionid,
						'partnerid' => $partnerid,
						'role' => Partner::ROLE_CANDIDATE,
						'status' => Partner::STATUS_DEFAULT));
					$partner->create();
				}
			}
		}
		Fox\Message::Success(Msg(Hive::BUNDLE,Hive::MSG_MISSION_CONTACTS_ASSIGNED,$nbContact));
	}
	catch (Fox\Object\Exception\NotExist $e)
	{
		Fox\Message::Error($e->getMessage());
	}
	echo $xview->messages(false,true);
}